# coding : UTF-8
"""
author：BingBO   time：2022.11.11
Theme：
notes：
"""
import cv2 as cv
import numpy as np


def laser1_Extract(L1img):
    print("****************** laser1_Extract ******************")
    Red = L1img[:, :, 2]  # B0 G1 R2
    _, threshold = cv.threshold(Red, 190, 255, cv.THRESH_BINARY)  # 转为二值图
    laser1_threshold = cv.medianBlur(threshold, 3)

    # cv.imshow('laser1_threshold', laser1_threshold)
    cv.imwrite(r"F:\MVS_Data\laser1_threshold.jpg", laser1_threshold)

    hight, width = laser1_threshold.shape
    # 将上面的重叠光条去掉
    for col in range(width):
        n = 0
        for row in range(hight - 1, 0, -1):
            diff = int(laser1_threshold[row - 1, col]) - int(laser1_threshold[row, col])  # 上一行像素值减去下一行像素值
            if diff > 0:
                n += 1
            if n > 1 and laser1_threshold[row, col] != 0:  # 将上面的重叠光条去掉
                laser1_threshold[row, col] = 0

    # cv.imshow('remove', laser1_threshold)
    cv.waitKey(0)
    cv.destroyAllWindows()

    lightList = np.sum(laser1_threshold, axis=1)  # 1 行相加, 变成一列
    ret = np.where(lightList > 0)  # 返回（索引+ 数据类型 ）
    lightIdx = ret[0]
    # print("lightIdx:", lightIdx)

    # 求laser1光条的上间断点行坐标
    LeftShift = np.roll(lightIdx, -1)  # 向下移动一位
    # print("LeftShift:", LeftShift)
    differList = lightIdx - LeftShift
    # print("differList:", differList)
    temp = differList.tolist()
    row_gapUp = lightIdx[temp.index(min(differList))]

    # 求laser1光条的下间断点行坐标
    RightShift = np.roll(lightIdx, 1)  # 向下移动一位
    # print("RightShift:", RightShift)
    differList = lightIdx - RightShift
    # print("differList:", differList)
    temp = differList.tolist()
    row_gapDn = lightIdx[temp.index(max(differList))]

    # 计算特征点坐标
    n, sumRow = 0, 0
    for col in range(width):  # 遍历这一行的每一列
        if laser1_threshold[row_gapUp, col] != 0:
            n += 1
            sumRow += (col + 1)  # 重心在第几列
    indexCol1 = int(sumRow / n) - 1  # 化为坐标索引
    P1 = [indexCol1, row_gapUp]  # 行，列

    n, sumRow = 0, 0
    for col in range(width):  # 遍历这一行的每一列
        if laser1_threshold[row_gapDn, col] != 0:
            n += 1
            sumRow += (col + 1)  # 重心在第几列
    indexCol2 = int(sumRow / n) - 1  # 化为坐标索引
    P2 = [indexCol2, row_gapDn]

    L1img[row_gapUp, indexCol1] = [255, 0, 0]
    L1img[row_gapDn, indexCol2] = [255, 0, 0]

    # 计算焊缝中点
    Pmid = [int((P1[0] + P2[0]) / 2), int((P1[1] + P2[1]) / 2)]
    print("焊缝中点特征点：", Pmid)
    cv.circle(L1img, [Pmid[1], Pmid[0]], 1, (255, 0, 255), -1)
    cv.circle(L1img, [Pmid[1], Pmid[0]], 5, (255, 0, 255), 1)

    # cv.imshow('L1img', L1img)
    cv.imwrite(r"F:\MVS_Data\L1img.png", L1img)

    return Pmid, P1, P2


def laser2_Extract(L2img):
    print("****************** laser1_Extract ******************")
    Red = L2img[:, :, 2]  # B0 G1 R2
    _, threshold = cv.threshold(Red, 190, 255, cv.THRESH_BINARY)  # 转为二值图
    laser2_threshold = cv.medianBlur(threshold, 3)

    cv.imshow('laser2_threshold', laser2_threshold)
    cv.imwrite(r"F:\MVS_Data\laser2_threshold.jpg", laser2_threshold)

    hight, width = laser2_threshold.shape

    # 将下面的重叠光条去掉
    for col in range(width):
        n = 0
        for row in range(hight - 1):
            diff = int(laser2_threshold[row + 1, col]) - int(laser2_threshold[row, col])  # 下一行像素值减去上一行像素值
            if diff > 0:
                n += 1
            if n > 1 and laser2_threshold[row, col] != 0:  # 将上面的重叠光条去掉
                laser2_threshold[row, col] = 0

    # cv.imshow('remove', laser2_threshold)
    cv.waitKey(0)
    cv.destroyAllWindows()

    lightList = np.sum(laser2_threshold, axis=1)  # 1 行相加, 变成一列
    ret = np.where(lightList > 0)  # 返回（索引+ 数据类型 ）
    lightIdx = ret[0]
    # print("lightIdx:", lightIdx)

    # 求laser1光条的上间断点行坐标
    LeftShift = np.roll(lightIdx, -1)  # 向下移动一位
    # print("LeftShift:", LeftShift)
    differList = lightIdx - LeftShift
    # print("differList:", differList)
    temp = differList.tolist()
    row_gapUp = lightIdx[temp.index(min(differList))]

    # 求laser1光条的下间断点行坐标
    RightShift = np.roll(lightIdx, 1)  # 向下移动一位
    # print("RightShift:", RightShift)
    differList = lightIdx - RightShift
    # print("differList:", differList)
    temp = differList.tolist()
    row_gapDn = lightIdx[temp.index(max(differList))]

    # 计算特征点坐标
    n, sumRow = 0, 0
    for col in range(width):  # 遍历这一行的每一列
        if laser2_threshold[row_gapUp, col] != 0:
            n += 1
            sumRow += (col + 1)  # 重心在第几列
    indexCol1 = int(sumRow / n) - 1  # 化为坐标索引
    P1 = [indexCol1, row_gapUp]

    n, sumRow = 0, 0
    for col in range(width):  # 遍历这一行的每一列
        if laser2_threshold[row_gapDn, col] != 0:
            n += 1
            sumRow += (col + 1)  # 重心在第几列
    indexCol2 = int(sumRow / n) - 1  # 化为坐标索引
    P2 = [indexCol2, row_gapDn]

    L2img[row_gapUp, indexCol1] = [255, 0, 0]
    L2img[row_gapDn, indexCol2] = [255, 0, 0]

    # 计算焊缝中点
    Pmid = [int((P1[0] + P2[0]) / 2), int((P1[1] + P2[1]) / 2)]
    print("焊缝中点特征点：", Pmid)
    cv.circle(L2img, [Pmid[1], Pmid[0]], 1, (255, 0, 255), -1)
    cv.circle(L2img, [Pmid[1], Pmid[0]], 5, (255, 0, 255), 1)

    # cv.imshow('L2img', L2img)
    cv.imwrite(r"F:\MVS_Data\L2img.png", L2img)

    return Pmid, P1, P2

    '''
    # 计算光条数量的方法不适合Square，在焊缝处的工件上会有激光残影存在
    # 轮廓近似方法：cv.CHAIN_APPROX_SIMPLE  cv.CHAIN_APPROX_NONE：存储所有的轮廓点
    contours, _ = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)  # 耗内存
    print("轮廓个数:", len(contours))  # 轮廓的个数
    # 当轮廓面积<阈值，将该轮廓用0填充
    for i in range(len(contours)):
        area = cv.contourArea(contours[i])  # 轮廓面积
        print(area)
        if area < 100:
            cv.drawContours(binary, [contours[i]], 0, 0, -1)
    cv.imshow('remove%d' % mode, binary)
    '''
